package a02;

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatBox extends JPanel implements ActionListener, Constants{
    private static final long serialVersionUID = 1L;
    private JScrollPane scrollPane;
    private JTextArea chatArea;
    private JPanel chatBox;
    private JTextField textField;
    private JPanel mainBox;
    private RegularControl<?> control;

    public ChatBox(RegularControl<?> control, int frameHeight) {
	chatArea = new JTextArea(frameHeight / 19, 25);
	textField = new JTextField(25);
	scrollPane = new JScrollPane(chatArea);
	chatBox = new JPanel();
	mainBox = new JPanel();
	GridBagConstraints constraints = new GridBagConstraints();
	this.control = control;

	mainBox.setLayout(new FlowLayout());
	chatBox.setLayout(new BoxLayout(chatBox, BoxLayout.PAGE_AXIS));
	chatBox.setBorder(BorderFactory.createBevelBorder(1));
	chatArea.setEditable(false);
	chatArea.setFont(FONT_CHAT);

	textField.addActionListener(this);
	constraints.gridwidth = GridBagConstraints.REMAINDER;
	constraints.fill = GridBagConstraints.BOTH;
	chatBox.add(scrollPane, constraints);
	constraints.fill = GridBagConstraints.HORIZONTAL;
	chatBox.add(textField, constraints);
	mainBox.add(chatBox);

	this.add(mainBox);
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
	String text = textField.getText();
	if (!(text.equals(""))) {
	    this.addChatText(text);
	}
	textField.setText("");
    }

    private void addChatText(String text) {
	try {
	    if (control.getServer() != null) {
		if (chatArea.getText().length() > 0)
		    chatArea.append("\n");
		chatArea.append(control.getServer().getPlayerName(control.getPlayerID())+": "+text);
		control.getServer().setChatText(chatArea.getText());		
	    }
	} catch (RemoteException e) {
	    e.printStackTrace();
	}
    }

    public void checkForNews() throws RemoteException {
	if (control.getServer() != null
		&& control.getServer().getChatTextSize() > chatArea.getText()
			.length()) {
	    chatArea.setText(control.getServer().getChatText());

	}
    }

}
